package com.security.manage.search.controller;

import com.security.manage.search.model.*;
import com.security.manage.search.repository.FireWalInfoRepository;
import com.security.manage.search.repository.UsbKeyStaticsRepository;
import com.security.manage.search.service.UserMicroService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class AnaysisController {

    @Resource
    private FireWalInfoRepository fireWalInfoRepository;

    @Resource
    private UserMicroService userMicroService;

    @Resource
    private UsbKeyStaticsRepository usbKeyStaticsRepository;

    private List<String> vpnList;

    private Logger logger =LoggerFactory.getLogger(this.getClass());

    @Scheduled(cron = "0 0/5 * * * ?")
    public void updateVpnList(){
        vpnList = userMicroService.vpnList();
    }

    @GetMapping("/behavior/trace")
    public ResData behaviorTrace(SearchDto dto){

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (StringUtils.isNotEmpty(dto.getDeptIds())) {
            String[] idArray = StringUtils.split(dto.getDeptIds(), ",");
            List<Long> ids = Arrays.stream(idArray)
                    .map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
            boolQueryBuilder.must(QueryBuilders.termsQuery("deptId",ids));
        }

        if (dto.getUserId() != null && dto.getUserId()!=0L) {
            boolQueryBuilder.must(QueryBuilders.termQuery("userId",dto.getUserId()));
        }

        if (StringUtils.isEmpty(dto.getEnd())){
            dto.setEnd(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }

        if (dto.getStart() != null) {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("dateTime").gte(dto.getStart()).lte(dto.getEnd()));
        }else {
            boolQueryBuilder.must(QueryBuilders.rangeQuery("dateTime").lte(dto.getEnd()));
        }

        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
        nativeSearchQueryBuilder.withPageable(PageRequest.of(dto.getPage(),dto.getSize()));
        nativeSearchQueryBuilder.withSort(SortBuilders.fieldSort("dateTime").order(SortOrder.DESC));
        Page<FireWallInfo> pageInfos = fireWalInfoRepository.search(nativeSearchQueryBuilder.build());

        if (vpnList==null||vpnList.size()==0){
            vpnList = userMicroService.vpnList();
        }

        List<TraceDto> dtos = new ArrayList<>();
        pageInfos.get().forEach(fireWallnfo -> {
            TraceDto dto1 = new TraceDto();
            dto1.setAccessTime(fireWallnfo.getDateTime());

            if(vpnList.contains(fireWallnfo.getDestIp())){
                dto1.setVpnInfo(fireWallnfo.getDestIp());
            }else {
                dto1.setDestIp(fireWallnfo.getDestIp());
            }
            dto1.setSrcIp(fireWallnfo.getSrcIp());
            dtos.add(dto1);
        });

        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("count",pageInfos.getTotalElements());
        resultMap.put("data",dtos);

        return new ResData(1,"获取成功",resultMap);
    }

    private DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @GetMapping("/usbKey/detail")
    public ResData getUsbKeyRelationData(String usbKey){

        List<UsbKeyStatics> list = usbKeyStaticsRepository.findByUsbKey(usbKey);
        List<Map<String,Object>> resultList = new ArrayList<>();

        if (list.size()==0){
            return new ResData(1,"暂无数据",resultList);
        }
        Map<String, List<UsbKeyStatics>> collect = list.stream().collect(Collectors.groupingBy(UsbKeyStatics::getAssetNumber));
        for (String key:collect.keySet()){
            Map<String,Object> map = new HashMap<>();
            map.put("usbKey",usbKey);
            map.put("assetNumber",key);
            List<UsbKeyStatics> statics = collect.get(key);
            map.put("number",statics.size());
            StringBuffer sb = new StringBuffer();
            for (UsbKeyStatics us:statics){
                sb.append("(").append(us.getStartTime().format(dtf)).append(",").append(us.getEndTime().format(dtf)).append("),");
            }
            map.put("time",sb.substring(0,sb.length()-1));
            resultList.add(map);
        }
        return new ResData(1,"获取数据成功",resultList);
    }

}
